<template>
  <div id="app">
    <div>
      <span>图书名称:</span>
      <input type="text" v-model.trim="addCh"  @keyup.enter= "addChange()"/>
    </div>
    <div>
      <button @click="addChange">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <BookHead/>
        <subject
        v-for="(item,index) in list" :key="index" :lists = "item"
        @delts = "getData()"
        :lit = " list"
        @changeCheck = "changeCheck"
        />
      </table>
    </div>
  </div>
</template>
<script>
import Head from './components/Head'
import subject from './components/subject'
import axios from 'axios'
axios.defaults.baseURL = 'http://liufusong.top:4000/'
export default {
  data () {
    return {
      list: [],
      addCh: '',
      ids: ''
    }
  },

  created () {
    this.getData()
  },

  methods: {
    // 请求参数
    async getData () {
      try {
        const res = await axios({
          url: 'books'
        })
        this.list = res.data
      } catch (err) {
        alert('请求失败了')
      }
    },
    // 添加/修改
    async addChange () {
      if (this.addCh === '') return alert('不能为空')
      if (this.ids) {
        console.log(888)
        try {
          await axios({
            url: 'books/' + this.ids,
            method: 'PUT',
            data: { name: this.addCh }
          })
          this.getData()
        } catch (err) {
          alert(err, '提交请求失败')
        }
        this.ids = false
        return (this.addCh = '')
      } else {
        console.log(666)
        try {
          await axios({
            url: 'books',
            method: 'POST',
            data: { name: this.addCh }
          })
          this.getData()
        } catch (err) {
          alert('上传失败了')
        }
        this.addCh = ''
      }
    },
    // 查讯图书信息
    changeCheck (datas) {
      this.addCh = datas.name
      this.ids = datas.id
      datas.name = ''
    }

  },
  components: {
    [Head.name]: Head,
    subject
  }

}
</script>
